import Vue from 'vue'
import router from './router'
import store from './store'
import { Toast } from 'vant'
import { ACCESS_TOKEN, INDEX_MAIN_PAGE_PATH, USER_INFO } from '@/store/mutation-types'
import { generateIndexRouter, setDefaultGrid } from "@/utils/util"
import { postAction } from '@/api/manage'
import whiteList from './white-list.js'
import { open } from '@/utils/router'

router.beforeEach(async (to, from, next) => {
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  }
  if (Vue.ls.get(ACCESS_TOKEN)) {
    const redirect = decodeURIComponent(from.query.redirect || to.path)

    /* has token */
    if (to.path === '/user/zwAppLogin') {
      next()
    } else if (to.path === '/user/zwtAppLogin') {
      next()
    } else {

      if (to.path === redirect) {
        // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
        // next({ ...to, replace: true })
        next();
      } else {
        // 跳转到目的路由
        next({ path: redirect })
      }
      return;
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // next({ path: '/user/login', query: { redirect: to.fullPath } })
      const appToken = to.query.accessToken;
      if (appToken) {
        store.dispatch('AppLogin', { token: appToken }).then(res => {
          next();
        }).catch(error => {
          next({ path: '/error' })
        })
      } else {
        next({ path: '/user/login' })
      }
    }
  }
})

router.beforeEach((to, from, next) => {
  if (to.path == '/404') {
    Toast({ position: 'top', message: '无权限访问' })
  } else {
    next()
  }
})

router.afterEach((to) => {
  const APP_TYPE = Vue.ls.get("LOGIN_APP_TYPE");
  if (APP_TYPE == 'ZWT') {
    WadeMobile.setH5TopBar({
      title: '四张网建优甩帽',
      share: false,
      copy: false,
      titleAlign: 'center',
      back: true,
      exit: true,
      refresh: false
    });
  }

  // 添加页面访问日志
  if (to.path != '/user/login' && to.path != '/user/zwAppLogin') {
    postAction('/system/saveSysHitsLog', {
      url: to.path,
      terminalType: 'app',
      title: to.meta.title,
      gridId: localStorage.getItem('$gridId'),
      params: JSON.stringify(to.query)
    })
  }
})